import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'join_group_state.dart';
import '../../../core/repository/default_api.dart';
import '../../../core/services/storage_service.dart';

class JoinGroupLogic extends GetxController {
  final state = JoinGroupState();
  final _api = DefaultApi();
  
  final groupCodeController = TextEditingController();

  @override
  void onClose() {
    groupCodeController.dispose();
    super.onClose();
  }

  /// 扫描二维码
  Future<void> scanQRCode() async {
    try {
      // 跳转到扫描页面
      final scannedCode = await Get.toNamed('/qr-scanner');
      
      // 如果扫描到了二维码
      if (scannedCode != null && scannedCode is String && scannedCode.isNotEmpty) {
        await _joinGroupWithCode(scannedCode);
      }
    } catch (e) {
      print('扫描二维码失败: $e');
      Toast.show('扫描失败，请检查相机权限');
    }
  }

  /// 加入群组（通过输入）
  Future<void> joinGroup() async {
    final groupCode = groupCodeController.text.trim();
    
    if (groupCode.isEmpty) {
      Toast.show('请输入群组码');
      return;
    }

    await _joinGroupWithCode(groupCode);
  }

  /// 使用群组码加入群组
  Future<void> _joinGroupWithCode(String groupCode) async {
    if (state.isJoining.value) return;

    try {
      state.isJoining.value = true;

      // 获取用户登录账号作为 applyInfo
      final userName = StorageService.to.getUserName() ?? '用户';

      final response = await _api.applyJoinGroupPost(
        applyInfo: userName, // 使用登录账号
        groupCode: groupCode,
        joinType: '2', // 2: 申请加入
        isShowLoading: true,
      );
      if (response != null && response['code'] == 200) {
        Toast.show('申请已发送，等待群主审批');
        groupCodeController.clear(); // 清空输入框
        Get.back(result: true); // 返回并刷新列表
      } else {
        Toast.show(response?['msg'] ?? '加入失败，请检查群组码是否正确');
      }
    } catch (e) {
      print('加入群组失败: $e');
      Toast.show('加入失败: $e');
    } finally {
      state.isJoining.value = false;
    }
  }
}
